from flask import Blueprint, render_template, request, jsonify, redirect, url_for, g, session

from apps.article import articleDao
from apps.user.userDao import selectUserById

article_bp = Blueprint('article', __name__, url_prefix='/article')

# 允许自由进入的路由
allow_route = ['/user/', '/user/userLogin', '/user/userLogout']


# 钩子函数
@article_bp.before_app_request
def before_app():
    if request.path not in allow_route and request.path[0:7] != '/static':
        uid = session.get('uid')
        if not uid:
            return redirect(url_for('user.index'))
        else:
            g.user = selectUserById(uid)
    else:
        pass


# 发表文章页面
@article_bp.route('/articleAdd')
def articleAdd():
    return render_template('article/articleAdd.html', user=g.user)


# 发表文章
@article_bp.route('/articleSave', methods=['POST', 'GET'])
def articleSave():
    if request.method == 'POST':
        userId = session.get('uid')
        title = request.form.get('title')
        content = request.form.get('content')
        articleDao.articleAdd(userId, title, content)
        return redirect(url_for('user.mainPage'))
    else:
        return redirect(url_for('article.articleAdd'))


# 文章预览
@article_bp.route('/articleDetail')
def articleDetail():
    articleId = request.args.get('articleId')
    articleDao.updateFavNumByArticleId(articleId)
    article = articleDao.QueryArticleByArticleId(articleId)
    favFlag = articleDao.checkFav(g.user[0], articleId)
    comments = articleDao.QueryComments(articleId)
    return render_template('article/articleDetail.html', article=article, user=g.user, favFlag=favFlag,
                           comments=comments)


# 收藏文章
@article_bp.route('/articleFav')
def articleFav():
    userId = request.args.get("userId")
    articleId = request.args.get("articleId")
    fav_num = articleDao.articleFav(userId, articleId)
    return jsonify(fav_num=fav_num)


# 取消收藏文章
@article_bp.route('/articleDeFav')
def articleDeFav():
    userId = request.args.get("userId")
    articleId = request.args.get("articleId")
    fav_num = articleDao.articleDeFav(userId, articleId)
    return jsonify(fav_num=fav_num)


# 添加评论
@article_bp.route('/addComment', methods=['POST', 'GET'])
def addComment():
    if request.method == 'POST':
        userId = g.user[0]
        articleId = request.form.get('articleId')
        comment = request.form.get('commentTextarea')
        articleDao.addComment(userId, articleId, comment)
        return redirect(url_for('article.articleDetail', articleId=articleId))
    else:
        return redirect('user.mainPage')


# 模糊查询文章
@article_bp.route('/searchArticle', methods=['POST', 'GET'])
def searchArticle():
    if request.method == 'POST':
        title = request.form.get('title')
        articles = articleDao.QueryArticleByTitle(title)
        return render_template('article/searchArticleList.html', user=g.user, articles=articles)
    else:
        return redirect('user.mainPage')
